package com.heima.user.service.impl;

import com.heima.common.constants.user.UserRelationConstants;
import com.heima.common.exception.CustException;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.threadlocal.AppThreadLocalUtils;
import com.heima.model.user.dtos.UserRelationDTO;
import com.heima.model.wemedia.pojos.ApUser;
import com.heima.user.service.ApUserRelationService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

/**
 * @package com.heima.user.service.impl
 * @Date 2022/3/7
 * @project heima-leadnews
 */
@Service
public class ApUserRelationServiceImpl implements ApUserRelationService {
    @Autowired
    StringRedisTemplate redisTemplate;
    @Override
    public ResponseResult follow(UserRelationDTO dto) {
        //校验参数
        if (dto.getAuthorApUserId()==null){
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID);
        }
        Short operation = dto.getOperation();
        if (operation==null||(operation.intValue()!=0&&operation.intValue()!=1)){
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID,"关注类型错误");

        }
        ApUser user = AppThreadLocalUtils.getUser();
        if (user==null){
            CustException.cust(AppHttpCodeEnum.NEED_LOGIN);
        }
        Integer loginId = user.getId();
        Integer followId = dto.getAuthorApUserId();
        //判断是否是关注自己
        if (loginId.equals(followId)){
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST,"不可以自己关注自己");
        }
        //    校验之前有没有关注过   zscore
        Double score = redisTemplate.opsForZSet().score(UserRelationConstants.FOLLOW_LIST + loginId, String.valueOf(followId));
        if (operation.intValue()==0&&score!=null){
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST,"你已关注，请勿重复关注");
        }
        //    参数1： key   参数2: 要查询集合元素
        try {
            if (operation.intValue()==0){
                redisTemplate.opsForZSet().add(UserRelationConstants.FOLLOW_LIST+loginId,String.valueOf(followId),System.currentTimeMillis());
                redisTemplate.opsForZSet().add(UserRelationConstants.FANS_LIST+followId,String.valueOf(loginId),System.currentTimeMillis())  ;
            }else {
                redisTemplate.opsForZSet().remove(UserRelationConstants.FOLLOW_LIST+loginId,String.valueOf(followId));
                redisTemplate.opsForZSet().remove(UserRelationConstants.FANS_LIST+followId,String.valueOf(loginId));

            }
        } catch (Exception e) {
            e.printStackTrace();
            CustException.cust(AppHttpCodeEnum.SERVER_ERROR);
        }

        return ResponseResult.okResult();
    }
}
